package com.sam.core.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.dispatcher.Dispatcher;
import org.springframework.util.StringUtils;

import com.opensymphony.xwork2.inject.Container;

/**
 * Request相关工具类
 * @project EMan
 * @author Sam
 * @version
 * @date Feb 17, 2009 10:44:32 AM
 */
public class RequestUtils {

	private static final int MAX_AGE = -1;

	public Cookie makeValidCookie(HttpServletRequest request, String cookieName, String cookieValue) {
		Cookie cookie = new Cookie(cookieName, cookieValue);
		cookie.setMaxAge(MAX_AGE);
		cookie.setPath(StringUtils.hasLength(request.getContextPath()) ? request.getContextPath()
				: "/");
		return cookie;
	}

	// 获取struts.xml配置值
	public static String getConfig(String key) {
		Container con = Dispatcher.getInstance().getConfigurationManager().getConfiguration()
				.getContainer();

		return con.getInstance(String.class, key);
	}

	public Cookie makeValidCookie(HttpServletRequest request, String cookieName,
			String cookieValue, int maxAge) {
		Cookie cookie = new Cookie(cookieName, cookieValue);
		cookie.setMaxAge(maxAge);
		cookie.setPath(StringUtils.hasLength(request.getContextPath()) ? request.getContextPath()
				: "/");
		return cookie;
	}

	public static void cancelCookie(HttpServletRequest request, HttpServletResponse response,
			String cookieName) {
		response.addCookie(makeCancelCookie(request, cookieName));
	}

	private static Cookie makeCancelCookie(HttpServletRequest request, String cookieName) {
		Cookie cookie = new Cookie(cookieName, null);
		cookie.setMaxAge(0);
		cookie.setPath(StringUtils.hasLength(request.getContextPath()) ? request.getContextPath()
				: "/");
		return cookie;
	}
}
